<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <a-row >
        <div :class="advanced ? null: 'fold'" >
            <a-col :md="10" :sm="24" >
              <a-form-item
                label="表单编码"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 10, offset: 2}">
                <a-input v-model="queryParams.formId"/>
              </a-form-item>
            </a-col>
             <a-col :md="10" :sm="24" >
              <a-form-item
                label="表单名称"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 10, offset: 2}">
                 <a-input v-model="queryParams.formName"/>
              </a-form-item>
            </a-col>
        </div>
          <span style="float: right; margin-top: 3px;">
            <a-button type="primary" @click="search">查询</a-button>
            <a-button style="margin-left: 8px" @click="reset">重置</a-button>
          </span>
        </a-row>
      </a-form>
    </div>
    <div>
      <div class="operator">
        <a-button type="primary" ghost @click="addForm({})" >新增</a-button>
        <a-button @click="batchDelete" >删除</a-button>
      </div>
      <!-- 表格区域 -->
      <a-table ref="TableInfo"
               :columns="columns"
               :rowKey="record => record.formId"
               :dataSource="dataSource"
               :pagination="pagination"
               :loading="loading"
               :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
               :scroll="{ x: 900 }"
               @change="handleTableChange">
        <template slot="email" slot-scope="text">
          <a-popover placement="topLeft">
            <template slot="content">
              <div>{{text}}</div>
            </template>
            <p style="width: 150px;margin-bottom: 0">{{text}}</p>
          </a-popover>
        </template>
        <template slot="operation" slot-scope="text, record">
          <a  @click="editForm(record)" title="编辑">编辑</a>
          <a  @click="viewForm(record)" title="预览">预览</a>
          <a  @click="copyForm(record)" title="复制">复制表单</a>
        </template>
      </a-table>
    </div>
    <!-- 表单编辑 -->
    <form-config ref="FormConfig" @success="handleFormConfigSuccess"></form-config>
    <!-- 预览表单 -->
    <view-form ref="ViewForm"></view-form>
  </a-card>
</template>

<script>
import FormConfig from './FormConfig'
import ViewForm from './ViewForm'

export default {
  name: 'FormManage',
  components: {FormConfig, ViewForm},
  data () {
    return {
      advanced: false,
      queryParams: {},
      sortedInfo: null,
      paginationInfo: null,
      dataSource: [],
      selectedRowKeys: [],
      loading: false,
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      }
    }
  },
  computed: {
    columns () {
      let { sortedInfo } = this
      sortedInfo = sortedInfo || {}
      return [
        {
          title: '表单编码',
          dataIndex: 'formId',
          sorter: true,
          sortOrder: sortedInfo.columnKey === 'formId' && sortedInfo.order
        },
        {
          title: '表单名称',
          dataIndex: 'formName',
          sorter: true,
          sortOrder: sortedInfo.columnKey === 'formName' && sortedInfo.order
        },
        {
          title: '创建时间',
          dataIndex: 'createdDate',
          sorter: true,
          sortOrder: sortedInfo.columnKey === 'createdDate' && sortedInfo.order
        }, {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }]
    }
  },
  mounted () {
    this.fetch()
  },
  methods: {
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    addForm (record) {
      record.formJson = FormConfig.initJSON
      this.$refs.FormConfig.onOpen(record)
    },
    editForm (record) {
      this.$refs.FormConfig.onOpen(record)
    },
    viewForm (record) {
      this.$refs.ViewForm.onOpen(record)
    },
    handleFormConfigSuccess () {
      this.search()
    },
    copyForm (record) {
      let data = {}
      Object.assign(data, record)
      data.formName = data.formName + '-copy'
      data.createdDate = null
      data.formId = null
      this.$post('form', {
        ...data
      }).then((res) => {
        if (res.data.status) {
          this.$message.success('复制成功')
          this.search()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的记录')
        return
      }
      let that = this
      this.$confirm({
        title: '确定删除所选中的记录?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除',
        centered: true,
        onOk () {
          let formIds = []
          let selectedRowKeysStr = ',' + that.selectedRowKeys.join(',') + ','
          formIds.push(that.dataSource.filter(f => { return selectedRowKeysStr.indexOf(',' + f.formId + ',') > -1 }).map(m => { return m.formId }))
          that.$delete('form/' + formIds.join(',')).then((res) => {
            if (res.data.status) {
              that.$message.success(res.data.message)
              that.selectedRowKeys = []
              that.search()
            } else {
              that.$message.error(res.data.message)
            }
          })
        },
        onCancel () {
          that.selectedRowKeys = []
        }
      })
    },
    search () {
      let {sortedInfo, filteredInfo} = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...filteredInfo
      }, this.queryParams)
    },
    reset () {
      // 取消选中
      this.selectedRowKeys = []
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
      // 重置列过滤器规则
      this.filteredInfo = null
      // 重置列排序规则
      this.sortedInfo = null
      // 重置查询参数
      this.queryParams = {}
      this.fetch()
    },
    handleTableChange (pagination, filters, sorter) {
      // 将这三个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination
      this.filteredInfo = filters
      this.sortedInfo = sorter

      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters
      }, this.queryParams)
    },
    fetch (params = {}, querypas) {
      // 显示loading
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }
      this.$get('form', {
        ...params, ...querypas
      }).then((r) => {
        let data = r.data
        const pagination = { ...this.pagination }
        pagination.total = data.total
        this.dataSource = data.rows
        this.pagination = pagination
        // 数据加载完毕，关闭loading
        this.loading = false
      })
    }
  }
}
</script>
<style lang="less" scoped>
@import "../../../../static/less/Common";
</style>
